package com.xy.tianyu

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.view.KeyEvent
import android.view.View
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.BarUtils
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.xy.tianyu.view.CoolIndicatorLayout
import kotlinx.android.synthetic.main.activity_web.*


class WebActivity : BaseActivity() {
    private lateinit var url:String
    private lateinit var mAgentWeb:AgentWeb
    private lateinit var mCoolIndicatorLayout:CoolIndicatorLayout
    override fun showDestroyReveal(): Boolean = true
    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {

        }
    }
    private val mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            tv_web_title.text = title
        }
    }

    companion object{
        private const val INTENT_URL:String = "intent_url"

        fun actionStart(context: Context, webUrl: String){
            val intent = Intent(context, WebActivity::class.java)
            intent.putExtra(INTENT_URL, webUrl)
            context.startActivity(intent)
        }
    }
    override fun getLayoutId(): Int {

        return R.layout.activity_web
    }

    override fun initView() {
        mCoolIndicatorLayout = CoolIndicatorLayout(this)

        iv_web_back.setOnClickListener {
            if (!mAgentWeb.back()) {
                finish()
            }
        }
    }

    override fun initData() {
        url = intent.getStringExtra(INTENT_URL)
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(ll_web_container, LinearLayout.LayoutParams(-1, -1))
            .setCustomIndicator(mCoolIndicatorLayout)
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(mWebViewClient)
            .createAgentWeb()
            .ready()
            .go(url)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun onPause() {
        mAgentWeb.webLifeCycle.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb.webLifeCycle.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        mAgentWeb.webLifeCycle.onDestroy()
        super.onDestroy()
    }
}